
def a1107_1146():
    '''
    作用：可以查看dataset图片目录里所有文件中有多少是图片类型，张数，图片的名字
    '''
    from pathlib import Path
    import os
    import glob

    help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
    img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng']
    path = 'D:\python\Aclass\\1\myselfV1\data\JPEGImages'     # dataset的路径
    try:
        f = []  # image files
        for p in path if isinstance(path, list) else [path]:
            p = str(Path(p))  # os-agnostic
            parent = str(Path(p).parent) + os.sep
            if os.path.isfile(p):  # file
                with open(p, 'r') as t:
                    t = t.read().splitlines()
                    f += [x.replace('./', parent) if x.startswith('./') else x for x in t]  # local to global path
            elif os.path.isdir(p):  # folder    要是输入的是目录的话，就把目录里面所有的文件都加载进来
                f += glob.iglob(p + os.sep + '*.*')
            else:
                raise Exception('%s does not exist' % p)
        img_files = sorted(
            [x.replace('/', os.sep) for x in f if os.path.splitext(x)[-1].lower() in img_formats])  # 要是符合后缀名规则，就再数理一下路径
    except Exception as e:
        raise Exception('Error loading data from %s: %s\nSee %s' % (path, e, help_url))

    n = len(img_files)  # 符合要求的图片数有多少
    assert n > 0, 'No images found in %s. See %s' % (path, help_url)
    print(n)

def a1107_1333():
    import os
    import torch
    from tqdm import tqdm
    from PIL import Image,ExifTags
    import numpy as np

    for orientation in ExifTags.TAGS.keys():        # 这一段是解决PIL读取图片的时候自动旋转的问题，从服务器中读取时自动旋转的问题
        if ExifTags.TAGS[orientation] == 'Orientation':
            break

    def exif_size(img):
        # Returns exif-corrected PIL size       解决自动旋转问题的
        s = img.size  # (width, height)
        try:
            rotation = dict(img._getexif().items())[orientation]
            if rotation == 6:  # rotation 270
                s = (s[1], s[0])
            elif rotation == 8:  # rotation 90
                s = (s[1], s[0])
        except:
            pass

        return s

    def get_hash(files):
        # Returns a single hash value of a list of files
        return sum(os.path.getsize(f) for f in files if os.path.isfile(f))

    img_files = ['D:\\python\\Aclass\\yolov5-master\\data\\coco128\\images\\train2017\\000000000009.jpg',
                 'D:\\python\\Aclass\\yolov5-master\\data\\coco128\\images\\train2017\\000000000025.jpg'
                 ]
    label_files = ['D:\\python\\Aclass\\yolov5-master\\data\\coco128\\labels\\train2017\\000000000009.txt',
                   'D:\\python\\Aclass\\yolov5-master\\data\\coco128\\labels\\train2017\\000000000025.txt']

    def cache_labels(path):
        x={}
        pbar = tqdm(zip(img_files, label_files), desc='Scanning images', total=len(img_files))
        for (img, label) in pbar:
            try:
                l = []
                image = Image.open(img)
                image.verify()  # PIL verify
                # _ = io.imread(img)  # skimage verify (from skimage import io)
                shape = exif_size(image)  # image size
                assert (shape[0] > 9) & (shape[1] > 9), 'image size <10 pixels'
                if os.path.isfile(label):
                    with open(label, 'r') as f:
                        l = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)  # labels
                if len(l) == 0:
                    l = np.zeros((0, 5), dtype=np.float32)
                x[img] = [l, shape]
            except Exception as e:
                x[img] = [None, None]
                print('WARNING: %s: %s' % (img, e))

        x['hash'] = get_hash(label_files + img_files)
        torch.save(x, path)  # save for next time
        return x

    cache_path = 'D:\python\Aclass\yolov5-master\data\coco128\labels\\train2017.cache'
    if os.path.isfile(cache_path):
        cache = torch.load(cache_path)  # load
        if cache['hash'] != get_hash(label_files + img_files):  # dataset changed
            cache = cache_labels(cache_path)  # re-cache
    else:
        cache = cache_labels(cache_path)  # cache



if __name__ == '__main__':
    # a1107_1146()
    a1107_1333()